import os
import csv
import time
import requests
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

UUID = time.strftime('%Y-%m-%_d%H:%M:%S', time.localtime())
WEIBOMAIN_PATH = "/var/jenkins_home/workspace/WeiboMain"
allOnLineFileName = "./{}/allonline.csv".format(UUID)
whiteList = str(os.environ.get('scanwhitelist')).split(",")
url = 'http://abtest.client.weibo.cn/downloadAllOnlineData?token=nieyu2'
blackPathList = ['WBPlayerInternalExt', "FFmpeg", "IJKPlayer", "xcconfigs"]  # 不用扫描的黑名单
scanTimes = 0
problemABs = []


def loadAB():
    leng = 1
    print('开始拉取全量开关...')
    while (leng == 1):
        response = requests.get(url)
        leng = len(list(response.iter_content(1024)))  # 下载区块数
        if (leng == 1):
            print('下载失败')  # 如果是1 就是空文件 重新下载
        else:
            print('下载完成')

    allonline = []
    with open(allOnLineFileName, 'wb') as f:
        for chunk in response.iter_content(1024):  # 防止文件过大，以1024为单位一段段写入
            f.write(chunk)
    print('所有的全量开关已下载到{} 文件中。路径:{}'.format(allOnLineFileName, os.getcwd()))

    print('开始处理全量开关文件...')
    isScanAll = len(whiteList) == 1 and whiteList[0].lower() == 'all'
    if isScanAll:
        print('扫描全业务的问题开关')
    else:
        print("扫描业务组:" + ''.join(whiteList))
 
    with open(allOnLineFileName, 'r', encoding='utf-8') as f:
        reader = csv.DictReader(f, delimiter='\t')
        for line in reader:
            value = line["试验名称"]
            # 如果白名单存在 则只扫描白名单内的业务组
            if not isScanAll:
                group = line["项目组"]
                if group not in whiteList:
                    continue
            # 过滤命名带android的开关
            if "android" in value:
                continue
            else:
                allonline.append(value)
    # 将需要检验的开关列表写本地
    tem = allonline
    final_ABs_path = "./{}/final_ABs.txt".format(UUID)
    with open(final_ABs_path, 'w', encoding='utf-8') as f:
        for row in tem:
            f.write("%s\n" % row)
    print("处理完成 将结果写到{} 文件中。{}".format(final_ABs_path, os.getcwd()))
    return allonline


def search(dirname, abNames):
    global scanTimes
    global problemABs
    filenames = os.listdir(dirname)
    for filename in filenames:
        if filename.startswith("."):
            continue
        if filename in blackPathList:
            continue
        fullFileName = os.path.join(dirname, filename)
        if os.path.isdir(fullFileName):
            search(fullFileName, abNames)
        else:
            if os.path.exists(fullFileName):
                ext = os.path.splitext(fullFileName)[-1]
                if ext == '.m' or ext == '.mm':
                    try:
                        with open(fullFileName, 'r', encoding='utf-8') as f:
                            scanTimes += 1
                            for line in f:
                                for ab in abNames:
                                    if ab in line and ab not in problemABs:
                                        problemABs.append(str(ab).strip())
                                        print("😄找到未下开关:{} 文件名:{}".format(ab, fullFileName))
                                        break
                    except PermissionError:
                        print("error")


# 将结果写本地
def final(problemABList):
    problemABPath = "./{}/problem_ab.txt".format(UUID)
    with open(problemABPath, 'w', encoding='utf-8') as f1:
        for row in problemABList:
            f1.write("%s\n" % row)
    print("将找到问题的文件写到{} 文件中。{}".format(problemABPath, os.getcwd()))

    finalList = []
    with open(allOnLineFileName, 'r', encoding='utf-8') as f:
        reader = csv.reader(f)
        finalList.append(next(reader))  # header

        for li in reader:
            for ab in problemABList:
                if str(li).strip().find(ab) != -1:
                    finalList.append(li)
                    break

    if (len(finalList) - 1) != 0:
        out_file = "./{}/result.csv".format(UUID)
        with open(out_file, "w", encoding='utf-8') as out_csv:
            writer = csv.writer(out_csv)
            for row in finalList:
                writer.writerow(row)
        print("总共{}条数据写入到{}文件中 文件路径:{}".format(len(finalList) - 1, out_file, os.getcwd()))
    else:
        print("没有问题开关对应的负责人...")


def scan(abNames):
    print('开始扫描开关...')
    startTime = time.time()
    search(WEIBOMAIN_PATH, abNames)
    endTime = time.time()
    print('扫描完成')
    if len(problemABs) != 0:
        final(problemABs)
    print('\n 总共检测了:{}个文件 扫描了:{}个开关 耗时:{}秒'.format(scanTimes, len(abNames), endTime-startTime))


def send_mail(file_path):
    # 账号信息
    account = "xiaodong32@staff.sina.com.cn"
    password = "Woai710102!"
    receivers = str(os.environ.get('receivers'))
    to_addrs = receivers.split(",")
    print("构建参数account:", account)
    print("构建参数password:", password)
    print("构建参数to_addrs:", to_addrs)
    # 构建正文
    content = "附件全部开关"
    # 构造附件
    attachment = MIMEText(open(file_path, 'rb').read(), 'base64', 'utf-8')
    attachment['Content-Type'] = 'application/octet-stream'
    attachment['Content-Disposition'] = 'attachment;filename="result.csv"'
    # 构造消息体
    message = MIMEMultipart()
    message['From'] = account
    message['To'] = receivers
    message['Subject'] = 'iOS已全量开关还存在代码的开关'
    message.attach(MIMEText(content, 'plain', 'utf-8'))
    message.attach(attachment)
    # 邮件配置
    smtpObj = smtplib.SMTP('mail.staff.sina.com.cn')
    smtpObj.login(account, password)
    err = smtpObj.sendmail(account, to_addrs, message.as_string())
    if err:
        print("邮件发送失败")
    else:
        print("邮件发送成功")


if __name__ == '__main__':
    dir = "./{}".format(UUID)
    if not os.path.exists(dir):
        os.makedirs(dir)
    abNames = loadAB()
    scan(abNames)
    filename = os.path.abspath(os.curdir) + "/" + UUID + '/result.csv'
    if os.path.exists(filename):
        send_mail(file_path=filename)
        print("发送邮件成功")
    else:
        print("文件不存在")
